﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TSCC.Interface;
using TSCC.WinControl;

namespace TSCC.WinApp
{
    public partial class frmExceptionLog : Form
    {
        string mode = string.Empty;
        CRUDMode currentMode = CRUDMode.None;
        TSCC.Service.Service_ExceptionLog log = null;
        TSCC.Interface.iUser CSR = null;
        ControlMatrix[] ucControls = null;
        string[] itemNotEmpty = {"CALL OUT"
                                ,"客訴回電或處理"
                                ,"英/日語回電"
                                ,"各項業務追蹤(需經監控台同意)"
                                ,"警示帳戶"
                                ,"基金類"};
            

        public frmExceptionLog(TSCC.Interface.iUser p_usr)
        {
            InitializeComponent();
            ucCRUD1.CRUDClick += new EventHandler(ucCRUD1_CRUDClick);
            ucGV.GVCellEvent += new DataGridViewCellEventHandler(ucGV_GVCellEvent);
            CSR = p_usr;
            FillExceptionItem();
            FillUCControlToArray();
            log = new TSCC.Service.Service_ExceptionLog();
            setAllControlDisable();
        }

        // TOOD: 這有空要改一下先..XD
        void ucGV_GVCellEvent(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow gvRow = ((DataGridView)sender).CurrentRow;            
            ucException.SetValue(gvRow.Cells["例外項目"].Value);
            ucStartTime.SetValue(gvRow.Cells["例外時間起"].Value);
            ucEndTime.SetValue(gvRow.Cells["例外時間迄"].Value);
            ucResult.SetValue(gvRow.Cells["實際產能"].Value);
            ucNone.SetValue(gvRow.Cells["聯絡未果"].Value);
            ucNote.SetValue(gvRow.Cells["備註"].Value);
        }

        private void FillUCControlToArray()
        {
            ucControls = new ControlMatrix[]
                {
                    ucException 
                    ,ucStartTime
                    ,ucEndTime
                    ,ucResult
                    ,ucNone
                    ,ucNote
                    ,ucCSRInfo1
                };
        }

        private void FillExceptionItem()
        {
            ucException.SetData(TSCC.Service.Utility.GetExceptionList());
        }

        void ucCRUD1_CRUDClick(object sender, EventArgs e)
        {

            /*
             * 2012-03-01 這應該可以直接取而不用問button
             * ucBtn btn = sender as ucBtn;
             *currentMode = btn.ButtonnMode; 
             */
            //
            
            changeState();            
        }

        void changeState()
        {
            currentMode = ucCRUD1.CurrentMode;
            switch ((int)currentMode)
            { 
                case (int)CRUDMode.Insert:
                    insert();
                    break;
                case (int)CRUDMode.Exit:
                    exit();
                    break;
                case (int)CRUDMode.Cancel:
                    setAllControlDisable();
                    clearValue();
                    break;
                case (int)CRUDMode.Query:
                    query();
                    break;
                case (int)CRUDMode.InsertExecute:
                    insertExecute();
                    break;
                case (int)CRUDMode.Update:
                    update();
                    break;
                case (int)CRUDMode.UpdateExecute:
                    updateExecute();
                    break;
                case (int)CRUDMode.Delete:
                    deleteExecute();
                    break;
                case (int)CRUDMode.QueryExecute:
                    queryExecute();
                    break;
            }

        }

        private void exit()
        {
            this.Dispose();
        }
       
        private void frmExceptionLog_Load(object sender, EventArgs e)
        {
            ucCSRInfo1.SetUserInfo(CSR);
            this.Select();
        }

        void insertExecute()
        {
            if (!this.Validate())
            {
                return;
            }



            int iResult, iNone;
            iResult = Convert.ToInt32(ucResult.TextBoxText.Length == 0
                                ? "0" : ucResult.TextBoxText);
            iNone = Convert.ToInt32(ucNone.TextBoxText.Length == 0
                                ? "0" : ucNone.TextBoxText);

            iCMBItem itm = ucException.GetSelectItem();
            string msg = string.Empty;
            bool result = false;
            result = log.Insert(
                    CSR.GetEmployeeNo()
                    , CSR.GetUserName()
                    , CSR.GetTeam()
                    , Convert.ToString(itm.GetItemValue())
                    , ucStartTime.TextBoxText
                    , ucEndTime.TextBoxText
                    , iResult
                    , iNone
                    , ucNote.TextBoxText
                    , ucCSRInfo1.GetToday(string.Empty) );
            msg = result == true ? "新增成功" 
                        : string.Format("新增失敗→{0}",log.MSG);
            MessageBox.Show(msg);
            if (result == true)
            {
                queryExecute();
                //insert();
                ucCRUD1.SetMode(CRUDMode.Insert);
                changeState();
            }
        }

        void updateExecute()
        {
            if (!Validate())
            { return; }
            iCMBItem itm = ucException.GetSelectItem();
            string msg = string.Empty;
            bool result = false;
            result = log.Update(
                    CSR.GetEmployeeNo()
                    , CSR.GetUserName()
                    , Convert.ToString(itm.GetItemValue())
                    , ucStartTime.TextBoxText
                    , ucEndTime.TextBoxText
                    , Convert.ToInt32(ucResult.TextBoxText)
                    , Convert.ToInt32(ucNone.TextBoxText)
                    , ucNote.TextBoxText
                    , ucCSRInfo1.GetToday(string.Empty));
            msg = result == true ? "修改成功" : "修改失敗";
            MessageBox.Show(msg);
            if (result == true)
            {
                queryExecute();
            }
        }

        void queryExecute()
        {
            string today = ucCSRInfo1.GetToday(string.Empty);
            DataTable dt = log.GetData(CSR.GetEmployeeNo(), today, today);
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("沒有你查詢的資料");
                ucCRUD1.SetMode(CRUDMode.None);
                return;
            }
            else
            {
                //ucCRUD1.HaveDataMode();
                ucCRUD1.SetMode(CRUDMode.QueryAfter);
            }
            ucGV.SetData(dt);            
        }

        void deleteExecute()
        {
            string msg = string.Empty;
            bool result = false;
            result = log.Delete( CSR.GetEmployeeNo()
                    , ucStartTime.TextBoxText                    
                    , ucCSRInfo1.GetToday(string.Empty));
            msg = result == true ? "刪除成功" : "刪除失敗";
            MessageBox.Show(msg);
            if (result == true)
            {
                queryExecute();
            }

        }

        void setAllControlDisable()
        {
            foreach (ControlMatrix cnt in ucControls)
            {
                cnt.Enabled = false;
            }
            ucGV.NoData();
        }

        void query()
        {
            foreach (ControlMatrix cnt in ucControls)
            {
                cnt.ClearText();
                cnt.Enabled = false;
                if (cnt.AllowQuery)
                {
                    cnt.Enabled = true;
                }
            }
            ucCSRInfo1.Select();
            //ucCSRInfo1.Focus();
        }

        void clearValue()
        {
            foreach (ControlMatrix cnt in ucControls)
            {
                cnt.ClearText();
            }
        }

        void insert()
        {
            foreach (ControlMatrix cnt in ucControls)
            {
                cnt.ClearText();
                cnt.Enabled = false;
                if (cnt.AllowInsert)
                {
                    cnt.Enabled = true;
                }
            }
            ucException.Select();
            //ucCRUD1.SetMode(CRUDMode.InsertRunning);
        }

        //找到資料回來時
        void update()
        {
            foreach (ControlMatrix cnt in ucControls)
            {
                cnt.Enabled = false;
                if (cnt.AllowUpdate)
                {
                    cnt.Enabled = true;
                }
            }
            ucException.Select();
        }

        void Execute()
        { 
            
        }

        /// <summary>
        /// 把資料填入到control 中去
        /// </summary>
        void FillDataToControl()
        { }

        new bool Validate()
        {
            /*
             * 提報例外項目為下彆幾項才需要登「實際產能」「聯絡未果」兩欄位
                其餘項目不需要.. 
                call out
                客戶回電或處理
                英/日語回電
                各項業務追蹤(需經監控台同意)
                警示帳戶
                基金類
             */


            bool notEmpty = false; //預設可以空白
            iCMBItem itm = ucException.GetSelectItem();
            if (itm == null)
            {
                MessageBox.Show("例外項目不可空白!!");
                ucException.Select();
                return false;
            }

            //var xx = from abc in itemNotEmpty where abc == itm.GetItemValue() select abc;
            string itmValue = (string)itm.GetItemValue();
            if (Array.IndexOf<string>(itemNotEmpty, itmValue ) > -1) //只會找到一個
            {
                notEmpty = true;
            }

            if (ucStartTime.TextBoxText == string.Empty)
            {
                MessageBox.Show("例外開始時間不可空白!!");
                ucStartTime.Select();
                return false;
            }
            else
            {
                if (!Service.Utility.IsTimeFormat(ucStartTime.TextBoxText))
                {
                    MessageBox.Show("例外開始時間格式錯誤!! 請輸入 1300 24小時制");
                    ucStartTime.Select();
                    return false;
                }
            }

            if (ucEndTime.TextBoxText == string.Empty)
            {
                MessageBox.Show("例外結束時間不可空白!!");
                ucEndTime.Select();
                return false;
            }
            else
            {
                if (!Service.Utility.IsTimeFormat(ucEndTime.TextBoxText))
                {
                    MessageBox.Show("例外結束時間格式錯誤!! 請輸入 1300 24小時制");
                    ucEndTime.Select();
                    return false;
                }            
            }

            if (!log.ValidateStartEndTime(ucStartTime.TextBoxText
                    , ucEndTime.TextBoxText))
            {
                MessageBox.Show("結束時間不能大於開始時間！", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ucEndTime.Select();
                return false;
            }

            if ((ucResult.TextBoxText == string.Empty) & (notEmpty == true) )
            {
                MessageBox.Show("實際產能不可空白!!");
                ucResult.Select();
                return false;            
            }

            if( (ucNone.TextBoxText == string.Empty) & (notEmpty == true))
            {
                MessageBox.Show("聯絡未果不可空白!!");
                ucNone.Select();
                return false;
            }

            return true;
        }
    }
}
